import router from './router'
import store from './store'
import { Message } from 'element-ui'
import { loginex } from '@/api/user'
import NProgress from 'nprogress'
import 'nprogress/nprogress.css'
import { getToken, setToken, setHardID, getHardID, setToKey, removeToKey } from '@/utils/auth' // 获取token令牌

import { setPageTitle } from '@/utils/get-page-title' // 获取动态的title

import defaultSettings from '@/settings'

const { isFromCenter } = defaultSettings

const whiteList = ['/login', '/login2', '/auth-redirect', '/download', '/realTimeScreen', '/bigScreen', '/assetPanorama']

/** 从集中管理进来走这段处理 */
async function handleBeforeEachByDevice(to, from, next) {
  
  NProgress.start()
  setPageTitle(to.meta.title)

  const hardID = to.query.HardID
  
  let theHardID = getHardID()
  
  if (hardID && hardID !== theHardID) {
    theHardID = setHardID(hardID)
  }

  if (typeof theHardID === 'string' && theHardID !== '' && hardID !== theHardID) {
    
    next({
      path: to.path,
      query: Object.assign({}, to.query, { HardID: theHardID }),
      replace: true
    })
    NProgress.done()
    return
  }

  const token = getToken()
  
  if (token) {
    if (to.path === '/login') {
      next({ path: '/', replace: true })
    } else {
      const hasRoles = store.getters.roles && store.getters.roles.length > 0
      if (hasRoles) {
        next()
      } else {
        try {
          store.commit('user/SET_TOKEN', token)
          const { roles } = await store.dispatch('user/getInfo')
          
          // 根据角色生成可访问路由映射
          const accessRoutes = await store.dispatch('permission/generateRoutes', roles)
          // 动态添加可访问路由
          router.addRoutes(accessRoutes)
          next({ ...to, replace: true })
        } catch (error) {
          // 移除令牌，重定向值登录页面
          await store.dispatch('user/resetToken')
          Message.error(error || 'Has Error')
          next(`/login`)
          NProgress.done()
        }
      }
    }
  } else {
    if (to.path !== '/login' && whiteList.indexOf(to.path) !== -1) {
      next()
    } else {
      next(new Error('应前往集中管理登录'))
      // window.location.replace('/#/login');
    }
  }

  NProgress.done()
}

/** 默认路由处理 */
async function handleBeforeEach(to, from, next) {
  
    // 开始加载进度条
    NProgress.start()

    // 免密登录
    const toKey = to.query.toKey
    
    if (toKey) {
      try {
        const { Token } = await loginex({
          Header: {
            CmdCode: 'LoginEX'
          },
          Data: {
            Password: toKey
          }
        })

        if (Token) {
          setToKey(toKey)
          store.commit('user/SET_TOKEN', Token)
          setToken(Token)
          sessionStorage.setItem('username', 'root')
          next({ path: '/', replace: true })
        } else {
          throw new Error('免密登录失败')
        }
      } catch (error) {
        // 移除令牌，重定向值登录页面
        await store.dispatch('user/resetToken')
        next({ path: '/login', replace: true })
        NProgress.done()
      }
      return
    }

    // 设置页面标题
    // document.title = getPageTitle(to.meta.title)
    setPageTitle(to.meta.title)

    // 检查是否为白名单路由
    if (whiteList.includes(to.path)) {
      next() // 直接放行
      return
    }
    setPageTitle(to.meta.title)

    // 获取当前 token
    const hasToken = getToken()

    // 检查用户是否已登录（有 token 且有用户名）
    if (hasToken && sessionStorage.getItem('username')) {
      // 如果访问登录页，重定向到首页
      if (to.path === '/login') {
        next({ path: '/' })
        NProgress.done()
      } else {
        // 检查用户角色是否已加载
        const hasRoles = store.getters.roles && store.getters.roles.length > 0
        if (hasRoles) {
          next() // 角色已加载，直接放行
        } else {
          try {
            // 获取用户信息
            const { roles } = await store.dispatch('user/getInfo')
            // 根据角色生成动态路由
            const accessRoutes = await store.dispatch('permission/generateRoutes', roles)
            // 添加动态路由
            router.addRoutes(accessRoutes)
            // 重定向到目标路由，确保动态路由生效
            next({ ...to, replace: true })
          } catch (error) {
            console.error('getInfo 失败:', error)
            // 获取用户信息失败，重置 token 并跳转到登录页
            await store.dispatch('user/resetToken')
            next(`/login`)
            NProgress.done()
          }
        }
      }
    } else {
      removeToKey()
      // 无 token 或用户名，跳转到登录页
      next(`/login`)
      NProgress.done()
    }
}

router.beforeEach(isFromCenter ? handleBeforeEachByDevice : handleBeforeEach)


// 全局后置路由守卫，清理加载状态
router.afterEach(() => {
  // 结束加载进度条
  NProgress.done()
})